<?php

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018-8-9
 * Time: 下午 11:07
 */
class Model
{
    private $db;

    /*初始化*/
    function __construct()
    {
        require 'common.php';
        session_start();
        require_once getAbsolutePath(__DIR__, '../common/db/mysql.php');
        $this->db = new Table('tb_user');
    }

    /*验证中心*/
    public function login()
    {
        $data = null;
        //判断登录情况
        if (isset($_SESSION['username']) && isset($_SESSION['stoken'])) {
            //已经登录：返回用户信息给view处理
            $data = array(
                'username' => $_SESSION['username'],
                'stoken' => $_SESSION['stoken']
            );

        } else {
            if (isset($_POST['username']) && $_POST['password']) {
                //登录
                $result = $this->db->where('username=?', $_POST['username'])
                    ->where('password=?', $_POST['password'])
                    ->select()->fetch();
                if ($result) {
                    //登录成功：记录session信息
                    $stoken = array(
                        'stoken' => 'USER_STOKEN:' . $result['username'] . time()
                    );
                    $this->db->where('id=?', $result['id'])
                        ->update($stoken)
                        ->rowCount();
                    $_SESSION['username'] = $result['username'];
                    $_SESSION['stoken'] = $stoken['stoken'];
                    $data = array(
                        'username' => $_SESSION['username'],
                        'stoken' => $_SESSION['stoken']
                    );
                } else {
                    //登录失败
                    $data = false;
                }
            } else {
                $data = false;
            }
        }
        return $data;
    }
}